<?php

abstract class User_Abstract
{
    protected static $_dbh;
    
    protected $_userId;
    protected $_data = array();
    
    public function __construct($user_id)
    {
        if (!$user_id) {
            throw new Framework_Exception('Не передан user_id');
        }
        $this->_userId = $user_id;
    }

    /**
     * Возвращает user_id по логину
     * 
     * @param string $username 
     * @return int
     */
    public static function findUserIdByLogin($username)
    {
        return empty($username) ? null : Framework_Registry::get('dbh')->selectCell('SELECT user_id FROM user WHERE LOWER(user_login)=LOWER(?)', $username);
    }
    
    public static function findUserIdByPhone($phone)
    {
        return empty($phone) ? null : Framework_Registry::get('dbh')->selectCell('SELECT user_id FROM user WHERE user_number=?', $phone);
    }
    
    /**
     * Возвращает user_id по мылу
     * 
     * @param string $username 
     * @return int
     */
    public static function findUserIdByMail($mail)
    {
        return empty($mail) ? null : Framework_Registry::get('dbh')->selectCell('SELECT user_id FROM user WHERE LOWER(user_mail)=LOWER(?)', $mail);
    }
    
    /**
     * Возвращает логин по user_id
     * 
     * @param int $user_id
     * @return int
     */
    public static function findLoginByUserId($user_id)
    {
        return empty($user_id) ? null : Framework_Registry::get('dbh')->selectCell('SELECT user_login FROM user WHERE user_id=?', $user_id);
    }
    
    /**
     * Удаление записи из таблицы user
     *
     * @param int $user_id
     * @return int
     */
    public static function delete($user_id)
    {
        return empty($user_id) ? null : Framework_Registry::get('dbh')->query('DELETE FROM user WHERE user_id=?', $user_id);
    }
    
    /**
     * Отключение активации
     *
     * @param int $user_id
     * @return int
     */
    public static function disable($user_id)
    {
        return empty($user_id) ? null : Framework_Registry::get('dbh')
            ->query("UPDATE user SET user_active='0' WHERE user_id=?", $user_id);
    }
    
     /**
     * modifyed by kiote
     * Вовращает все данные по юзеру из таблички user
     * + все данные о жалобах на пользователя (из таблички abuse)
     * @return array
     */
    public function getAllData()
    {
    	$sql = "SELECT *, count(abuse_id) as abuse_count,
    	               (YEAR(CURRENT_DATE)-YEAR(user_born))
    	               - (RIGHT(CURRENT_DATE,5)<RIGHT(user_born,5)) AS user_age,
    	               UNIX_TIMESTAMP(user_block) AS block,
    	               UNIX_TIMESTAMP(user_last_visit) AS user_last_visit
                FROM `user` 
                LEFT JOIN abuse ON (abuse_user_id_to = user_id)
             	WHERE user_id=? 
				GROUP BY user_id";
        return self::$_dbh->selectRow($sql, $this->_userId);
    }

     /**
     * Список друзей
     * 
     * @return array 
     */
    public function getFriends($sum = 10, $page = 0, &$paging = array())
    {
        $result = self::$_dbh->selectPage($total_rows,
                                  "SELECT *, UNIX_TIMESTAMP(user_last_visit) AS user_last_visit
                                   FROM ?_user
                                   LEFT JOIN friend ON user_id = friend_user_id_to
                                   WHERE friend_user_id_from=?
                                   LIMIT ?d, ?d",
                                   $this->_userId,
                                   $page*$sum, $sum);
        $paging = paging($page, $sum, $total_rows);

        return $result;
    }
    
     /**
     * Список игнорируемых
     * 
     * @return array 
     */
    public function getBlockUsers($sum = 10, $page = 0, &$paging = array())
    {
        $result = self::$_dbh->selectPage($total_rows,
                                  "SELECT *, UNIX_TIMESTAMP(user_last_visit) AS user_last_visit
                                   FROM ?_user
                                   LEFT JOIN ?_block ON user_id = block_user_id_to
                                   WHERE block_user_id_from=?
                                   LIMIT ?d, ?d",
                                   $this->_userId,
                                   $page*$sum, $sum);
        $paging = paging($page, $sum, $total_rows);

        return $result;
    }
    
     /**
     * Вовращает user_id
     * 
     * @return array 
     */
    public function getUserId()
    {
        return $this->_userId;
    }

    public function getSettings()
    {
        return self::$_dbh->selectCol('SELECT user_meta_name AS ARRAY_KEY, user_meta_value
                                       FROM user_meta
                                       WHERE user_meta_user_id=?',
                                       $this->_userId);
    }
    
    public function setSettings($data)
    {
        foreach($data as $key => $value) {
            $rows = self::$_dbh
                ->query('UPDATE user_meta
                         SET user_meta_value=?
                         WHERE user_meta_user_id=? AND user_meta_name=?',
                         $value, $this->_userId, $key);
            if (!$rows) {
                @self::$_dbh
                    ->query('INSERT INTO user_meta
                             SET user_meta_value=?, user_meta_user_id=?, user_meta_name=?',
                             $value, $this->_userId, $key);
            }
        }
    }
}
